<?php

namespace app\controller\api;

use app\base\BaseEncryptController;
use app\model\game\GameProcessModel;
use app\model\game\GameTypeModel;
use app\model\game\GameUserModel;
use app\model\goods\GoodsModel;
use app\model\goods\GoodsTypeModel;
use app\model\order\OrderModel;
use app\model\user\UserBeanLogModel;
use app\model\user\UserBeanPredictModel;
use app\model\user\UserCouponModel;
use app\model\user\UserModel;
use think\Request;

/**
 * 盲盒游戏
 * Class Index
 * @package app\controller
 */
class Game extends BaseEncryptController
{
    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 获取趣豆商城的商品分类列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onGoodsType()
    {
        $goods_type_model = new GoodsTypeModel();
        $map = [
            'parent_id' => 0,
            'special' => 1
        ];
        $type_temp = $goods_type_model->where($map)->find();
        if (empty($type_temp)) {
            $out_data = [
                'code' => 1,
                'data' => [],
                'msg' => "获取成功"
            ];
            return self::returnMsg($out_data);
        }
        $type_arr = $goods_type_model->getChildList($type_temp['id'], "id,name,special,parent_id,sort,status", 0, 1);
        $out_data = [
            'code' => 1,
            'data' => $type_arr,
            'msg' => "获取成功"
        ];
        return self::returnMsg($out_data);
    }

    /**
     * 获取趣豆商城首页商品列表
     * @param int $type_id
     * @param int $page
     * @param int $limit
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onGoodsIndex($type_id = 0, $page = 1, $limit = 20)
    {
        $GoodsModel = new GoodsModel();
        $goodsField = "a.id as goods_id,a.goods_title,a.goods_img,a.goods_min_price,a.goods_min_unit,a.goods_min_market_price,a.goods_max_price,a.goods_up_count,a.goods_share_count,a.goods_collect_count,a.goods_read_count,a.goods_sale,a.goods_storage,a.goods_tag";
        //全部
        $map = [
            'a.goods_hot_status' => 2,
            'a.goods_status' => 1,
            'a.goods_special' => 0,
            'c.status' => 0
        ];
        $type_ids = [];
        if (!empty($type_id)) {
            $type_ids = GoodsTypeModel::getChildId($type_id);
        }
        //判断是否是认证商家
        $data = $GoodsModel
            ->alias('a')
            ->goodsType($type_ids)
            ->leftJoin("t_goods_type c", "a.goods_type_id=c.id")
            ->where($map)->order('a.sort desc,a.id desc')
            ->field($goodsField)
            ->limit(($page - 1) * $limit, $limit)
            ->select();

        $out_data = json_decode(json_encode($data), true);
        foreach ($out_data as &$value) {
            if (mb_strpos($value['goods_tag'], " ") > 0) {
                $value['goods_tag'] = mb_substr($value['goods_tag'], 0, mb_strpos($value['goods_tag'], " "));
            }
        }
        $rsps['list'] = array_merge($out_data);
        return self::returnMsg(1, $rsps);
    }

    /**
     * 获取趣豆商城礼包商品列表
     * @param int $page
     * @param int $limit
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function onGoodsGift($page = 1, $limit = 20)
    {
        $GoodsModel = new GoodsModel();
        $goodsField = "a.id as goods_id,a.goods_title,a.goods_img,a.goods_min_price,a.goods_min_unit,a.goods_min_market_price,a.goods_max_price,a.goods_up_count,a.goods_share_count,a.goods_collect_count,a.goods_read_count,a.goods_sale,a.goods_storage,a.goods_tag";
        //全部
        $map = [
            'a.goods_hot_status' => 2,
            'a.goods_special' => 3,
            'a.goods_status' => 1,
            'c.status' => 0
        ];
        $type_ids = [];
        if (!empty($type_id)) {
            $type_ids = GoodsTypeModel::getChildId($type_id);
        }
        //判断是否是认证商家
        $data = $GoodsModel
            ->alias('a')
            ->goodsType($type_ids)
            ->leftJoin("t_goods_type c", "a.goods_type_id=c.id")
            ->where($map)->order('a.sort desc,a.id desc')
            ->field($goodsField)
            ->limit(($page - 1) * $limit, $limit)
            ->select();

        $out_data = json_decode(json_encode($data), true);
        foreach ($out_data as &$value) {
            if (mb_strpos($value['goods_tag'], " ") > 0) {
                $value['goods_tag'] = mb_substr($value['goods_tag'], 0, mb_strpos($value['goods_tag'], " "));
            }
        }
        $rsps['list'] = array_merge($out_data);
        return self::returnMsg(1, $rsps);
    }

    /**
     * 获取趣味盲盒首页情况
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getGameCore()
    {
        $user_id = $this->currentUser['user_id'];   //登录信息
        $bean = UserModel::getBean($user_id);
        $bean_earnings = UserModel::getBeanEarnings($user_id);
        $bean = floatval($bean) + floatval($bean_earnings);

        $coupon = UserModel::getCoupon($user_id);
        $card = GameUserModel::getCardClassNum($user_id, 1);
        $box = GameUserModel::getCardClassNum($user_id, 2);
        $order = OrderModel::getOrderCount($user_id, 2);
        $map = [
            'user_id' => $user_id,
            'day' => date("Y-m-d")
        ];
        $game_model = new GameProcessModel();
        $pay = $game_model->where($map)->sum('number');
        $rem = 15 - $pay;
        $data = [
            'bean' => round($bean, 2),
            'coupon' => $coupon,
            'card' => $card,
            'box' => $box,
            'order' => $order,
            'rem' => $rem
        ];
        return self::returnMsg(1, $data);
    }

    /**
     * 参与盲盒游戏
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function joinGameProcess(Request $request)
    {
        $user_id = $this->currentUser['user_id'];   //登录信息
        $type = $request->param('type');      //1铜卡 2银卡 3金卡 4砖卡
        $number = $request->param('number');      //几连抽
        $out_data = GameProcessModel::addGameProcess($user_id, $type, $number);
        return self::returnMsg($out_data);
    }

    /**
     * 主动刷新开奖
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function openGameProcess()
    {
        $user_id = $this->currentUser['user_id'];//登录信息
        $out_data = GameProcessModel::upGameProcess($user_id);
        return self::returnMsg($out_data);
    }

    /**
     * 我的卡片
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getGameCardList(Request $request)
    {
        $user_id = $this->currentUser['user_id'];//登录信息
        $class = $request->param('class');      //1卡片,2盒子
        $card_model = new GameUserModel();
        $list_arr = [];
        $game_type = GameTypeModel::getTypeList();
        if (intval($class) == 1) {
            $map1 = [
                'user_id' => $user_id,
                'open' => 2,
                'settlement' => 0,
                'win' => 2
            ];
            $card_process_model = new GameProcessModel();
            $list_no = $card_process_model->where($map1)->field('type')->select();
            if (!empty($list_no)) {
                foreach ($list_no as $value) {
                    $name = "铜卡";
                    switch (intval($value['type'])) {
                        case 1:
                            $name = "铜卡";
                            break;
                        case 2:
                            $name = "银卡";
                            break;
                        case 3:
                            $name = "金卡";
                            break;
                        case 4:
                            $name = "钻卡";
                            break;
//                        case 5:
//                            $name = "铜盒";
//                            break;
//                        case 6:
//                            $name = "银盒";
//                            break;
//                        case 7:
//                            $name = "金盒";
//                            break;
//                        case 8:
//                            $name = "钻盒";
//                            break;
                    }
                    $list_arr[] = [
                        'name' => $name,
                        'bean' => $game_type[$value['type']]['bean'],
                        'coupon' => $game_type[$value['type']]['coupon'],
                        'id' => 0,
                        'type' => $value['type'],
                        'sum' => 1
                    ];
                }
            }
        }

        $map = [
            'user_id' => $user_id,
            'use' => 1,
            'class' => $class
        ];
        $list = $card_model->where($map)->field('count(id) as sum,name,type')->group('type')->select();
        if (!empty($list)) {
            foreach ($list as $value) {
                $list_arr[] = [
                    'name' => $value['name'],
                    'bean' => $game_type[$value['type']]['bean'],
                    'coupon' => $game_type[$value['type']]['coupon'],
                    'id' => 10,
                    'type' => $value['type'],
                    'sum' => $value['sum']
                ];
            }
        }
        $out_data = [
            'code' => 1,
            'data' => $list_arr
        ];
        return self::returnMsg($out_data);
    }

    /**
     * 开启卡盒
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function openGameCard(Request $request)
    {
        $user_id = $this->currentUser['user_id'];//登录信息
        $type = $request->param('type');      //1铜卡 2银卡 3金卡 4钻卡 5铜礼盒 6银礼盒 7金礼盒 8钻礼盒
        $out_data = GameUserModel::useCard($user_id, $type);
        return self::returnMsg($out_data);
    }

    /**
     *合成礼盒
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function comGameCard(Request $request)
    {
        $user_id = $this->currentUser['user_id'];    //登录信息
        $type = $request->param('type');      //1铜卡 2银卡 3金卡 4钻卡 5铜礼盒 6银礼盒 7金礼盒 8钻礼盒
        $out_data = GameUserModel::comCard($user_id, $type);
        return self::returnMsg($out_data);
    }

    /**
     * 获取盲盒记录
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getGameRecord()
    {
        $user_id = $this->currentUser['user_id'];//登录信息
        $data = GameProcessModel::getGameRecord($user_id);
        $out_data = [
            'code' => 1,
            'data' => $data
        ];
        return self::returnMsg($out_data);
    }

    /**
     * 获取趣豆记录
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserBean(Request $request)
    {
        $type = $request->param('type');
        $pagenow = $request->param('pagenow');
        $user_bean_model = new UserBeanLogModel();
        $user_id = $this->currentUser['user_id'];
        if (intval($type) == 1) {
            $type = ['recharge', 'add', 'sub', 'use', 'return'];
        } else {
            $type = "deposit";
        }
        $dataList = $user_bean_model->getPageData($type, $user_id, $pagenow, 12);
        $bean_capital = UserModel::getBean($user_id);
        $bean_earnings = UserModel::getBeanEarnings($user_id);
        //总的趣豆
        $bean = floatval($bean_capital) + floatval($bean_earnings);
        //冻结的趣豆
        $freeze_bean = UserModel::getBeanFreeze($user_id);
        //占用中的趣豆
        $occupied_bean = UserModel::getBeanOccupied($user_id);
        //可提现的趣豆
        $deposit_bean = $bean - floatval($freeze_bean);
        if ($deposit_bean < 0) {
            $deposit_bean = 0;
        }
        $deposit_bean = round($deposit_bean, 2);
        $list = json_decode(json_encode($dataList['dataList']), true);
        foreach ($list as &$value) {
            $value['check_str'] = "未审核";
            if (intval($value['check']) == 2) {
                $value['check_str'] = "已审核";
            }
            $value['add_time'] = date("Y-m-d H:i", $value['add_time']);
            $value['procedure'] = 0;
            //recharge 赠送 add活得 sub 扣除余额 use使用 deposit提现
            switch ($value['type']) {
                case 'recharge':
                case 'add':
                case 'return':
                    $value['symbol'] = "+";
                    break;
                case 'sub':
                case 'use':
                case 'deposit':
                    $value['symbol'] = "-";
                    if (floatval($value['deposit']) > 0) {
                        $value['procedure'] = round($value['bean'] - $value['deposit'], 2);
                    }
                    break;
            }
        }
        $out_data = [
            'code' => 1,
            'data' => [
                'list' => $list,
                'bean' => round($bean, 2),
                'freeze_bean' => round($freeze_bean, 2),
                'occupied_bean' => round($occupied_bean, 2),
                'deposit_bean' => round($deposit_bean, 2)
            ]
        ];
        return self::returnMsg($out_data);
    }

    /**
     * 获取用户总趣豆收益统计【过期】
     * @param Request $request
     * @return \think\response\Json
     */
    public function getUserTotalBean(Request $request)
    {
//        $start_time = $request->param('start_time');
//        $end_time = $request->param('end_time');
        $user_id = $this->currentUser['user_id'];
        $map = [
            'user_id' => $user_id,
            'earnings' => 2,
            'type' => 'add'
        ];
        $user_bean_log_model = new UserBeanLogModel();
        $bean_all = $user_bean_log_model->where($map)->sum('bean');
        $out_data = [
            'code' => 1,
            'data' => $bean_all,
            'msg' => "获取成功"
        ];
        return self::returnMsg($out_data);
    }

    /**
     * 获取用户总趣豆收益统计
     * @param Request $request
     * @return \think\response\Json
     */
    public function getUserStatisticsBean(Request $request)
    {
        $user_id = $this->currentUser['user_id'];
        $map = [
            'user_id' => $user_id,
            'earnings' => 2,
            'type' => 'add'
        ];
        $user_bean_log_model = new UserBeanLogModel();
        $mold_arr_sum = [2, 3, 4, 5];
        $bean_all = $user_bean_log_model->where($map)->whereIn('mold', $mold_arr_sum)->sum('bean');
        //本人参与收益累计
        $mold_arr = [2, 3];
        $bean_join_all = $user_bean_log_model->where($map)->whereIn('mold', $mold_arr)->sum('bean');
        //本人推广收益累计
        $mold_arr = [4, 5];
        $bean_pop_all = $user_bean_log_model->where($map)->whereIn('mold', $mold_arr)->sum('bean');

        $bean_day = UserBeanPredictModel::getEarningsSum($user_id, date("Y-m-d"));
        $bean_data = [
            'bean_all' => $bean_all,
            'bean_day' => $bean_day,
            'join_all' => $bean_join_all,
            'pop_all' => $bean_pop_all,
        ];
        $out_data = [
            'code' => 1,
            'data' => $bean_data,
            'msg' => "获取成功"
        ];
        return self::returnMsg($out_data);
    }

    /**
     * 用户总收益累计统计
     * @param Request $request
     * @return \think\response\Json
     */
    public function getUserTotalBeanPage(Request $request)
    {
//        $start_time = $request->param('start_time');
        $day = $request->param('day');
        $type = $request->param("type");
        $page = $request->param('page');
        $user_id = $this->currentUser['user_id'];
        if (empty($day)) {
            $day_time = time();
        } else {
            $day_time = strtotime($day);
        }
        $map = [
            'user_id' => $user_id,
            'earnings' => 2,
            'type' => 'add'
        ];
        if ($type == 1) {
            $mold_arr = [2, 3];
        } else {
            $mold_arr = [4, 5];
        }
        $user_bean_log_model = new UserBeanLogModel();
        $bean_log_list = $user_bean_log_model->field('day,SUM(bean) as bean_all')->where($map)->where('add_time', '<', $day_time)->whereIn('mold', $mold_arr)->group('day')->order('id DESC')->paginate(['page' => $page, 'list_rows' => 10], false);
        $out_data = [
            'code' => 1,
            'data' => $bean_log_list->items(),
            'msg' => "获取成功"
        ];
        return self::returnMsg($out_data);
    }

    /**
     * 趣豆提现
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function userBeanExtract(Request $request)
    {
        $price = $request->param('price');
        $openid = $request->param('openid');
        $user_id = $this->currentUser['user_id'];

        if (floatval($price) <= 0) {
            $out_data['code'] = 911;
            $out_data['msg'] = "参数有误";
            return self::returnMsg($out_data);
        }
        
        // $out_data['code'] = 0;
        // $out_data['msg'] = "账户金额不足";
        // return self::returnMsg($out_data);
            
        $w = date("w");
        if ($w == 6 || $w == 0) {
            $out_data['code'] = 0;
            $out_data['msg'] = "提现时间(周一到周五)";
            return self::returnMsg($out_data);
        }

        if (empty($user_id)) {
            $out_data['code'] = 0;
            $out_data['msg'] = "用户信息有误";
            return self::returnMsg($out_data);
        }

        if (floatval($price) < 50) {
            $out_data['code'] = 0;
            $out_data['msg'] = "提现额度必须大于50";
            return self::returnMsg($out_data);
        }

        if (floatval($price) > 200) {
            $return_data['code'] = 0;
            $return_data['msg'] = "单笔提现额度不得大于200";
            return $return_data;
        }

        $day_price = UserBeanLogModel::getDayDeposit($user_id);
        if (floatval($day_price + $price) >= 200) {
            $return_data['code'] = 0;
            $return_data['msg'] = "单日提现额度不得大于200";
            return $return_data;
        }

        $bean_capital = UserModel::getBean($user_id);
        $bean_earnings = UserModel::getBeanEarnings($user_id);

        //总的趣豆
        $bean = floatval($bean_capital) + floatval($bean_earnings);
        //冻结的趣豆
        $freeze_bean = UserModel::getBeanFreeze($user_id);

        //可提现的趣豆
        $deposit_bean = $bean - floatval($freeze_bean);
        if ($deposit_bean < 0) {
            $deposit_bean = 0;
        }

        if (floatval($price) <= floatval($deposit_bean)) {
            $out_data = UserBeanLogModel::changeEarnings($user_id, floatval($price), 'deposit', "用户趣豆提现", 6, $openid);
            if (empty($out_data['code'])) {
                return self::returnMsg($out_data);
            }
            if (intval($out_data['code']) == 1) {
                $id = $out_data['data'];
                $user_model = new  UserModel();
                $ret = $user_model->payUserDeposit('bean', $id);
                if ($ret['code'] == 1) {
                    return self::returnMsg($out_data);
                }
                $out_data = [
                    'code' => 0,
                    'msg' => "打款失败"
                ];
                return self::returnMsg($out_data);
            }
            return self::returnMsg($out_data);
        }

        $out_data['code'] = 0;
        $out_data['msg'] = "提现失败";
        return self::returnMsg($out_data);
    }

    /**
     * 获取优惠券列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function getCouponList(Request $request)
    {
        $user_id = $this->currentUser['user_id'];
        $page = $request->param('page');
        $coupon_model = new UserCouponModel();
        $coupon_list = $coupon_model->getPageData(1, $user_id, $page, 100);
        $out_data['code'] = 1;
        $out_data['data'] = $coupon_list['dataList'];
        $out_data['msg'] = "获取成功";
        return self::returnMsg($out_data);
    }

}
